import { App, Form, ModalProps } from 'antd';
import { t } from 'i18next';
import { useEffect, useMemo, useState } from 'react';

import externalSitesService from '@/api/services/externalSitesService';
import { Input, RequiredLabel, SimpleEditableSelect, TextArea } from '@/components/eai-design';
import Modals from '@/components/modals/Modals';
import { ExternalSite } from '@/types/nav/api';

interface NewSiteModalProps extends ModalProps {
  open: boolean;
  onCancel: () => void;
  site?: ExternalSite;
  tags: { label: string; value: string; id: string }[];
  onRefresh?: () => void;
}

const NewSiteModal = ({ open, site, tags, onCancel, onRefresh }: NewSiteModalProps) => {
  // 使用 useMemo 避免 defaultSite 作为 useEffect 依赖导致的每次渲染变化
  const defaultSite = useMemo<ExternalSite>(
    () => ({
      id: '',
      name: '',
      url: '',
      description: '',
      tag: '',
      image_url: '',
      sort_order: 0,
      created_at: '',
      updated_at: '',
      created_by: '',
    }),
    [],
  );
  const { message } = App.useApp();
  // useForm 只返回 form 实例，不传初始值
  const [form] = Form.useForm<ExternalSite>();
  const [loading, setLoading] = useState(false);

  // 导航类型选项
  const [tagOptions, setTagOptions] = useState([...tags]);

  const handleTagOptionsChange = async (
    options: { label: string; value: string; id?: string }[],
    type: 'add' | 'delete',
  ) => {
    console.log('options', options, type);
    // newOptions和tagOptions比较，获取新增的选项和删除的选项
    const addOptions = options.filter(
      (option) => !tagOptions.some((t) => t.value === option.value),
    );
    const deleteOptions = tagOptions.filter(
      (option) => !options.some((t) => t.value === option.value),
    );
    const option =
      type === 'add' ? addOptions[addOptions.length - 1] : deleteOptions[deleteOptions.length - 1];
    const res =
      type === 'add'
        ? await externalSitesService.createExternalSitesTag({
            name: option.label,
            sort_order: options.length + 1,
          })
        : await externalSitesService.deleteExternalSitesTag(option.id ?? '');
    if (res) {
      type === 'add'
        ? setTagOptions([...tagOptions, { label: res.name, value: res.name, id: res.id }])
        : setTagOptions(tagOptions.filter((t) => t.id !== option.id));
      return true;
    }
    return false;
  };

  const handleSubmit = async () => {
    if (loading) return;
    setLoading(true);
    try {
      const values = await form.validateFields();
      console.log('tagOptions', tagOptions, values, values.tag);
      const tag = tagOptions.find((t) => t.value === values.tag);
      const res = site
        ? await externalSitesService.updateExternalSite(site.id, {
            ...site,
            ...values,
            tag: tag?.label ?? '',
          })
        : await externalSitesService.createExternalSite({
            ...values,
            tag: tag?.label ?? '',
          });
      if (res) {
        message.success(site ? '编辑成功' : '新增成功');
        onRefresh && onRefresh();
        onCancel();
      } else {
        message.error(site ? '编辑失败' : '新增失败');
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setTagOptions([...tags]);
  }, [tags]);

  useEffect(() => {
    console.log('site', site);
    if (site) {
      form.setFieldsValue(site);
    } else {
      // 当site为空时，重置表单为默认值
      form.setFieldsValue(defaultSite);
    }
  }, [site, form, defaultSite]);

  // 监听Modal的open状态，当关闭时重置表单
  useEffect(() => {
    if (!open) {
      form.resetFields();
    }
  }, [open, form]);

  return (
    <Modals
      destroyOnHidden
      open={open}
      onCancel={onCancel}
      title={site ? `编辑${t('sys.menu.AINav')}` : `新增${t('sys.menu.AINav')}`}
      onOk={handleSubmit}
      width={380}
    >
      <Form layout="vertical" form={form}>
        <Form.Item
          label={<RequiredLabel>门户名称</RequiredLabel>}
          name="name"
          required={false}
          rules={[{ required: true, message: '请输入门户名称' }]}
        >
          <Input placeholder="请输入门户名称" />
        </Form.Item>
        <Form.Item label="门户描述" name="description">
          <TextArea placeholder="请输入门户描述" />
        </Form.Item>
        <Form.Item
          label={<RequiredLabel>门户地址</RequiredLabel>}
          name="url"
          required={false}
          rules={[{ required: true, message: '请输入门户地址' }]}
        >
          <Input placeholder="请输入门户地址" />
        </Form.Item>
        <Form.Item
          label={<RequiredLabel>门户类型</RequiredLabel>}
          name="tag"
          required={false}
          rules={[{ required: true, message: '请选择门户类型' }]}
        >
          <SimpleEditableSelect
            showSearch
            options={tagOptions}
            placeholder="请选择门户类型"
            onOptionsChange={handleTagOptionsChange}
            allowAdd
            maxLength={20}
            addButtonText="添加门户类型"
          />
        </Form.Item>
      </Form>
    </Modals>
  );
};

export default NewSiteModal;
